<?php
/**
 * 应用模块
 * 
 * @author ShuangYa
 * @package APIGateway
 * @category Model
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2017 ShuangYa
 * @license https://www.sylibs.com/go/apigateway/license
 */
namespace ag\model;

use yesf\library\ModelAbstract;
use ag\library\Cache;

class CompanionApp extends ModelAbstract {
	protected static $_table_name = 'app';
	protected static $_primary_key = 'id';

	public static function __callStatic($name, $arguments) {
		return self::getInstance()->$name(...$arguments);
	}
}

class App {
	const COLS = ['id', 'type', 'name', 'secret', 'permission', 'redirect_uri'];
	public static function get($id) {
		if (!is_int($id)) {
			return CompanionApp::get($id, self::COLS);
		}
		if (Cache::exists('app_' . $id)) {
			return swoole_unserialize(Cache::get('app_' . $id));
		} else {
			$rs = CompanionApp::get($id, self::COLS);
			if (empty($rs)) {
				return NULL;
			}
			if (!empty($rs['permission'])) {
				$rs['permission'] = swoole_unserialize($rs['permission']);
			} else {
				$rs['permission'] = [];
			}
			Cache::set('app_' . $id, swoole_serialize($rs));
			return $rs;
		}
	}
	public static function getSecret($id) {
		return self::get($id)['secret'];
	}
	public static function add($cols) {
		if (!isset($cols['permission']) || $cols['permission'] === NULL) {
			$cols['permission'] = ['user.token', 'user.get'];
		}
		$cols['permission'] = swoole_serialize(array_fill_keys($cols['permission'], 1));
		return CompanionApp::add($cols);
	}
	public static function del($id) {
		Cache::del('app_' . $id);
		CompanionApp::del($id);
	}
	public static function list($filter = [], $num = 30, $offset = 0) {
		$result = CompanionApp::list($filter, $num, $offset, self::COLS);
		foreach ($result as &$v) {
			if (!empty($v['permission'])) {
				$v['permission'] = swoole_unserialize($v['permission']);
			} else {
				$v['permission'] = [];
			}
		}
		return $result;
	}
	/**
	 * 更新应用
	 * @access public
	 * @param array $set
	 * @param array/int $filter
	 */
	public static function set($set, $filter) {
		if (isset($set['permission'])) {
			if (isset($set['permission'][0])) {
				$set['permission'] = swoole_serialize(array_fill_keys($set['permission'], 1));
			} else {
				$set['permission'] = swoole_serialize($set['permission']);
			}
		}
		Cache::del('app_' . $id);
		CompanionApp::set($set, $filter);
	}
	/**
	 * 检查App是否有调用某个API的权限
	 * @access public
	 * @param string $method API名称（形如user.add）
	 * @param array $app App信息
	 * @return boolean
	 */
	public static function checkPermission($method, $app) {
		return isset($app['permission'][$method]);
	}
}